/**
 * Created by Administrator on 2018/1/15.
 */
define(function(require, exports, module) {
    var $=require('zepto');
    cn=require('conment');
    drop=require('dropload');
    api=require('api')
    module.exports = {
        int:{
            wt_pageSize:'10',
            wt_pageNo:1,
            wt_type:10,
            tab_type:'mrmc',
            isDown:true,


            alloca_pageSize:'10',
            alloca_pageNo:1,
            alloca_type:10,
            alloca_type2:'ykfp',
            hisDown:true,


            down1:true,
            down2:true,


            codes:'',
            sellId:'',
            sellDateli:{},
        },
        getNowFormatDate:function () {
            var date = new Date();
            var seperator1 = "-";
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = year + seperator1 + month + seperator1 + strDate;
            return currentdate;
        },

        holdList:[],
        waterAjax:function (me) {
            const _this=this;
            cn.Ajax(api.dealList,{
                Length:_this.int.wt_pageSize,
                page:_this.int.wt_pageNo,
                tab:_this.int.tab_type,
            },function(c){
                if(c.flag==-100){
                    $("#today").html('<div class="zwsj" ><img src="../../images/home/kong.png"><p>请先登录，买卖你做主</p><a href="/view/login.html">立即登录</a></div>');
                    $('.dropload-down').addClass('down1')
                    _this.int.down1 = false
                    me.noData();
                    me.resetload();
                    return false
                }else {
                    const water = new Array();
                    const list = c.list;
                    var code = [];
                    if (_this.int.wt_pageNo == 1 && c.list.length < _this.int.wt_pageSize) {
                        $('.dropload-down').addClass('down1');
                        _this.int.down1 = false
                    }
                    if (c.list.length < _this.int.wt_pageSize) {
                        tab1LoadEnd = true;
                        me.noData();
                        _this.int.isDown = false;
                    }
                    if (_this.int.wt_pageNo == 1 && c.list.length == 0) {
                        $("#today").html('<div class="zwsj" ><img src="../../images/home/kong.png"><p>搭档出本金，买卖你做主</p><a href="/view/seach.html">立即发起交易</a></div>');
                        $('.dropload-down').addClass('down1');
                        _this.int.down1 = false;
                        me.resetload();
                        return false
                    }
                    if(list.length==0){
                        me.noData();
                        me.resetload();
                        return false
                    }
                    if(_this.int.wt_pageNo==1){
                        _this.holdList = list||[];
                    }else{
                        var len =list.length;
                        if(len>0){
                            for(var k=0;k<len;k++){
                                _this.holdList.push(list[k]);
                            }
                        }

                    }
                    $.each(_this.holdList, function (i, l, array) {
                        water.push('<li>');
                        water.push('<span class="deal-top-time ">买入：' + (l.applyTimeStr).substring(5, 10) + '</span>');
                        water.push('<div class="deal-li-content">');
                        water.push('<h3 class="cont-title detail ' + (l.type == 11 ? 'T1' :l.type == 10?'Mf': 'T5') + '" data-id="' + l.id + '">' + l.name + ' | ' + l.buyQuantityPlan + '股<span class="deal-bongd deal_price' + l.code + '"></span></h3>')
                        water.push('<div class="cont-detail"> ');
                        water.push('<div class="detail" data-id="' + l.id + '"> <p>' + l.amount + '</p> <span>交易本金</span> </div> ');
                        water.push('<div class="detail" data-id="' + l.id + '"> <p class="yingk ' + (parseFloat(l.amountDifference) >= 0 ? "red" : "green") + ' deal-yk' + i + '" data-buyprice="' + l.buyPricePlan + '" data-num="' + l.buyQuantityPlan + '" data-state="' + l.state + '" >' + (l.state < 4 ? "0.00" : (parseFloat(l.amountDifference) > 0 ? ("+" + l.amountDifference) : l.amountDifference)) + '</p> <span>交易盈亏</span> </div>');
                        if (l.state == 4) {
                            if(_this.getNowFormatDate()==(l.buyTimeStr).substring(0,10)){
                                water.push('<div><p>今日买入</p> <span class="origin">持仓中</span> </div> ');
                            }else{
                                water.push('<div><p><button type="button" class="btn-sell" data-id="' + l.id + '" data-num="' + l.buyQuantityPlan + '" data-amount="' + l.amount + '" data-name="' + l.name + l.code + '">通知卖出</button></p> <span class="origin">持仓中</span> </div> ');
                            }
                        } else {
                            water.push('<div><p>' + l.stateStr + '</p> <span class="origin">' + (l.state == 8 ? '' : '持仓中') + '</span> </div> ');
                        }
                        water.push('</div> ');
                        water.push('</div>');
                        water.push('</li>');
                        _this.int.codes += l.code + ',';
                    });
                    // 为了测试，延迟1秒加载
                    setTimeout(function () {
                        $('#today').html(water.join(''));
                        $('.detail').on('click', function () {
                            window.location.href = '/view/strategy_detail.html?id=' + $(this).data('id')
                        });
                        $('.btn-sell').on('click', function () {
                            _this.int.sellId = $(this).data('id');
                            $('#nameCode').text($(this).data('name'));
                            $('#amout').text($(this).data('amount') + '元');
                            $('#num').text($(this).data('num') + '股');
                            $("#dialog-yk").text($(this).parent().parent().siblings('div').children('.yingk').text())
                            $('#fudong').text($(this).parent().parent().parent().siblings().children('.deal-bongd').children('i').text());
                            if (parseFloat($(this).parent().parent().siblings('div').children('.yingk').text()) >= 0) {
                                $("#dialog-yk").addClass('red').removeClass('green')
                            } else {
                                $("#dialog-yk").addClass('green').removeClass('red')
                            }
                            $('.dialog').show();
                        })
                        ++_this.int.wt_pageNo;
                        me.resetload();
                    }, 500);
                }
            },'post');

        },
        sellDeal:function () {
            const _this=this;
            cn.loadHtml({
                txt:'正在通知搭档',
                time:1,
                is:true,
            });
            cn.Ajax(api.sell,{
                id : _this.int.sellId,
            },function(d){
                cn.loadHtml({
                    is:false,
                });
                if(d.flag==1){
                    cn.alert(d.message)
                    $('.dialog').hide();
                    setTimeout(function () {
                        window.location.reload()
                    },500)
                }else{
                    cn.alert(d.message)
                }

            },'post')
        },
        timeIndex_market:function () {
            const _this=this;
            cn.Ajax(api.url_stock.moreMarket,{
                codes :_this.int.codes,
            },function(d){
                const list=d;
                $.each(list,function(i,l,array){
                    var tradePrice=parseFloat(l.tradePrice),preClosePx=parseFloat(l.preClosePx),state=$('.deal-yk'+i).data('state'),
                        buyprice=parseFloat( $('.deal-yk'+i).data('buyprice')),num=parseFloat( $('.deal-yk'+i).data('num'));
                    if(state>=4&&state<8){
                        if(parseFloat(((tradePrice-buyprice)*num))>0){
                            $('.deal-yk'+i).text('+'+parseFloat((tradePrice-buyprice)*num).toFixed(2)).addClass('red').removeClass('green');
                        }else{
                            $('.deal-yk'+i).text(parseFloat((tradePrice-buyprice)*num).toFixed(2)).addClass('green').removeClass('red');
                        }
                    }
                    $('.deal_price'+l.code).html('<i>'+(tradePrice).toFixed(2)+'</i>&nbsp;&nbsp;'+(((tradePrice-preClosePx)/preClosePx)*100).toFixed(2)+'%')
                    if(tradePrice>=preClosePx){
                        $('.deal_price'+l.code).addClass('red').removeClass('green');
                    }else{
                        $('.deal_price'+l.code).addClass('green').removeClass('red');
                    }
                });
                setTimeout(function () {
                    _this.timeIndex_market()
                },3000)
            },'post')
        },
        loadTime:function () {
            const _this=this;
            if(this.int.codes.length!=0){
                _this.timeIndex_market()
            }else{
                setTimeout(function () {
                    _this.loadTime()
                },1000)
            }
        },

        historyList:[],
        allocation:function (me) {
            const _this=this;
            cn.Ajax(api.dealList,{
                Length:_this.int.alloca_pageSize,
                page:_this.int.alloca_pageNo,
                tab:_this.int.alloca_type2,
            },function(c){
                if(c.flag==-100){
                    $("#allocation").html('<div class="zwsj" ><img src="../../images/home/kong.png"><p>请先登录，买卖你做主</p><a href="/view/login.html">立即登录</a></div>');
                    $('.dropload-down').addClass('down2');
                    me.noData();
                    _this.int.down2=false;
                    me.resetload();
                    return false
                }else{
                    const water=new Array();
                    var list=c.list;
                    if(_this.int.alloca_pageNo==1&&c.list.length<_this.int.alloca_pageSize){
                        _this.int.down2=false;
                        $('.dropload-down').addClass('down2');
                    }
                    if(c.list.length<_this.int.alloca_pageSize){
                        tab2LoadEnd = true;
                        me.noData();
                        _this.int.hisDown=false;
                    }
                    if(_this.int.alloca_pageNo==1&&list.length==0){
                        $("#allocation").html('<div class="zwsj" ><img src="../../images/home/kong.png"><p>搭档出本金，买卖你做主</p><a href="/view/seach.html">立即发起交易</a></div>');
                        $('.dropload-down').addClass('down2');
                        _this.int.down2=false;
                        me.resetload();
                        return false
                    }
                    if(list.length==0){
                        me.noData();
                        me.resetload();
                        return false
                    }
                    if(_this.int.alloca_pageNo==1){
                        _this.historyList = list||[];
                    }else{
                        var len =list.length;
                        if(len>0){
                            for(var k=0;k<len;k++){
                                _this.historyList.push(list[k]);
                            }
                        }

                    }
                    $.each(_this.historyList,function(i,l,array){
                       var amountDifference=parseFloat(l.amountDifference),sellAmount=parseFloat(l.sellAmount),buyAmount=parseFloat(l.buyAmount);
                        water.push('<li class="detail" data-id="'+l.id+'">');
                        water.push('<span class="deal-top-time ">卖出：'+(l.sellTimeStr).substring(5,10)+'</span>');
                        water.push('<div class="deal-li-content">');
                        water.push('<h3 class="cont-title '+(l.type==11?'T1':'T5')+'">'+l.name+' | '+l.buyQuantityPlan+'股</h3>')
                        water.push('<span class="deal-bongd"></span>');
                        water.push('<div class="cont-detail"> ');
                        water.push('<div> <p>'+l.amount+'</p> <span>交易本金</span> </div> ');
                        water.push('<div> <p class="yingk '+(parseFloat(l.amountDifference)>=0?"red":"green")+'"  >'+(sellAmount-buyAmount).toFixed(2)+'</p> <span>交易盈亏</span> </div>');
                        water.push('<div><p class="'+(amountDifference>=0?"red":"green")+'">'+amountDifference+'</p> <span>'+(amountDifference>=0?"获得盈利":"亏损赔付")+'</span> </div> ');
                        water.push('</div> ');
                        water.push('</div>');
                        water.push('</li>');
                    });

                    setTimeout(function () {
                        $('#allocation').html(water.join(''));
                        ++_this.int.alloca_pageNo;
                        $('.detail').on('click',function () {
                            window.location.href='/view/strategy_detail.html?id='+$(this).data('id')
                        });
                        me.resetload();
                    }, 500);
                }
            },'post');

        },




        tab_futures:function(){
            var itemIndex = 0;
            var _this=this;
            var tab1LoadEnd = false;
            var tab2LoadEnd = false;
            var tab1top='';
            var tab2top='';
            $('#dynamic div').on('click',function(){
                var $this = $(this);
                itemIndex = $this.index();
                $this.addClass('tab-active').siblings('div').removeClass('tab-active');
                $('.lists').eq(itemIndex).show().siblings('.lists').hide();
                const Y = $('div.tab-active').offset().left;
                $(".tab-bod").animate({'margin-left':Y})
                // sss=document.documentElement.scrollTop;
                if(itemIndex == '0'){
                    $('.dropload-down').addClass(_this.int.down1?'':'down1').removeClass('down2')
                }else{
                    $('.dropload-down').addClass(_this.int.down2?'':'down2').removeClass('down1')
                }
                if(itemIndex == '0'&&_this.int.isDown){
                    // 如果数据没有加载完
                    tab2top=document.documentElement.scrollTop;
                    window.scrollTo(0, tab2top);
                    if(!tab1LoadEnd){
                        // 解锁
                        dropload.unlock();
                        dropload.noData(false);
                    }else{
                        // 锁定
                        dropload.lock('down');
                        dropload.noData();
                    }
                }else if(itemIndex == '1'&&_this.int.hisDown){
                    tab1top=document.documentElement.scrollTop;
                    window.scrollTo(0, tab1top);
                    if(!tab2LoadEnd){
                        dropload.unlock();
                        dropload.noData(false);
                    }else{
                        dropload.lock('down');
                        dropload.noData();
                    }
                }
                dropload.resetload();
            });
            var dropload = $('#view-content').dropload({
                scrollArea : window,
                threshold:100,
                loadUpFn : function(me){
                    // 加载菜单一的数据
                    if(itemIndex == '0'){
                        _this.int.wt_pageNo=1;
                        _this.int.wt_isDown=true;
                        // $("#today").html('');
                        _this.waterAjax(me)
                    }else if(itemIndex == '1'){
                        _this.int.alloca_pageNo=1;
                        _this.int.hisDown=true;
                        // $("#allocation").html('');
                        _this.allocation(me)
                    }
                },
                loadDownFn : function(me){
                    // 加载菜单一的数据
                    if(itemIndex == '0'){
                        _this.waterAjax(me);
                    }else if(itemIndex == '1'){
                        _this.allocation(me);
                    }
                }
            });
        },

        init:function () {
            const _this=this;
            _this.tab_futures();
            _this.loadTime();

            $('#confirm').on('click',function () {
                _this.sellDeal();
            });
            $('#close').on('click',function () {
                $('.dialog').hide();
            });
            if(!sessionStorage.getItem('testKey')){
                window.location.href='./login.html';
            }
            $('#accounts').on('click',function () {
                _this.int.tab_type='ykfp';
                _this.upDown();
            });
            $('#buy_sell').on('click',function () {
                _this.int.tab_type='mrmc';
                _this.upDown();
            });

        },
    }

});

